<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CCompanyInfoForm">
          <a-row>
						<a-col :span="12">
							<a-form-item label="公司名称" v-bind="validateInfos.companyName" id="CCompanyInfoForm-companyName" name="companyName">
								<a-input v-model:value="formData.companyName" placeholder="请输入公司名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="负责人" v-bind="validateInfos.person" id="CCompanyInfoForm-person" name="person">
								<a-input v-model:value="formData.person" placeholder="请输入负责人"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="负责人电话" v-bind="validateInfos.phone" id="CCompanyInfoForm-phone" name="phone">
								<a-input v-model:value="formData.phone" placeholder="负责人电话"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
<!--						<a-col :span="12">
							<a-form-item label="公司资质" v-bind="validateInfos.companyQualification" id="CCompanyInfoForm-companyQualification" name="companyQualification">
								<a-input v-model:value="formData.companyQualification" placeholder="请输入公司资质"  allow-clear ></a-input>
							</a-form-item>
						</a-col>-->
						<a-col :span="12">
							<a-form-item label="联系地址" v-bind="validateInfos.contactAddress" id="CCompanyInfoForm-contactAddress" name="contactAddress">
								<a-textarea v-model:value="formData.contactAddress" :rows="4" placeholder="请输入联系地址" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="其他备注" v-bind="validateInfos.otherRemarks" id="CCompanyInfoForm-otherRemarks" name="otherRemarks">
								<a-textarea v-model:value="formData.otherRemarks" :rows="4" placeholder="请输入其他备注" />
							</a-form-item>
						</a-col>

            <a-col :span="12">
              <a-form-item label="资质范围" v-bind="validateInfos.qualificationScope" id="CContractorInfoForm-qualificationScope" name="qualificationScope">
                <a-textarea v-model:value="formData.qualificationScope" :rows="4" placeholder="请输入资质范围" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="经营范围" v-bind="validateInfos.businessScope" id="CContractorInfoForm-businessScope" name="businessScope">
                <a-textarea v-model:value="formData.businessScope" :rows="4" placeholder="请输入经营范围" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="资质材料" v-bind="validateInfos.qualificationsFile" id="CProjectApplicationForm-qualificationsFile" name="qualificationsFile">
                <j-upload v-model:value="formData.qualificationsFile" dragger="true"   text="上传"  :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }"></j-upload>
              </a-form-item>
            </a-col>

            <a-divider >开票信息</a-divider >
            <a-col :span="1000">
              <InvoiceInfoModal :relevanceId="formData.id"  :snapContactId="snapContactId"></InvoiceInfoModal>
            </a-col>
<!--						<a-col :span="12">
							<a-form-item label="统一社会信用代码" v-bind="validateInfos.creditCode" id="CCompanyInfoForm-creditCode" name="creditCode">
								<a-input v-model:value="formData.creditCode" placeholder="请输入统一社会信用代码"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="银行名称" v-bind="validateInfos.bankName" id="CCompanyInfoForm-bankName" name="bankName">
							 <j-dict-select-tag showSearch="true"  v-model:value="formData.bankName" dictCode="bank_name" placeholder="请输入银行名称"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="支行信息" v-bind="validateInfos.branchInfo" id="CCompanyInfoForm-branchInfo" name="branchInfo">
								<a-input v-model:value="formData.branchInfo" placeholder="请输入支行信息"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="银行账号" v-bind="validateInfos.bankAccount" id="CCompanyInfoForm-bankAccount" name="bankAccount">
								<a-input v-model:value="formData.bankAccount" placeholder="请输入银行账号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="联行号" v-bind="validateInfos.cnapsCode" id="CCompanyInfoForm-cnapsCode" name="cnapsCode">
								<a-input v-model:value="formData.cnapsCode" placeholder="请输入联行号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="普票税率" v-bind="validateInfos.ordinaryTaxRate" id="CCompanyInfoForm-ordinaryTaxRate" name="ordinaryTaxRate">
								<a-input-number v-model:value="formData.ordinaryTaxRate" placeholder="请输入普票税率" style="width: 20%" />%
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="专票税率" v-bind="validateInfos.specializeTaxRate" id="CCompanyInfoForm-specializeTaxRate" name="specializeTaxRate">
								<a-input-number v-model:value="formData.specializeTaxRate" placeholder="请输入专票税率" style="width: 20%" />%
							</a-form-item>
						</a-col>-->


						
						
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate,getQueryById } from '../CCompanyInfo.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import CheckRuleModal from '@/views/bankInfo/CBankInfoListInfo.vue';
  import InvoiceInfoModal from '@/views/invoiceinfo/CInvoiceInfoListInfo.vue';
  import { buildShortUUID } from '@/utils/uuid';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const snapContactId = ref(''); //临时id
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    companyName: '',   
    contactAddress: '',   
    companyQualification: '',   
    creditCode: '',   
    bankName: '',   
	phone: '', 
	
    branchInfo: '',   
    bankAccount: '',   
    cnapsCode: '',   
	 person: '',   
    ordinaryTaxRate: undefined,
    specializeTaxRate: undefined,
    otherRemarks: '',   
	qualificationsFile:'',
	qualificationScope:'',
	businessScope:'',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    companyName: [{ required: true, message: '请输入公司名称!'},],
	//creditCode: [{ required: true, message: '请输入统一社会信用代码!'},],
	//bankName: [{ required: true, message: '请输入银行名称!'},],
	//bankAccount: [{ required: true, message: '请输银行账号!'},],
	//person: [{ required: true, message: '请输入负责人!'},],
	//phone: [{ required: true, message: '请输入负责人电话!'},],
	//ordinaryTaxRate: [{ required: true, message: '请输入普票税率!'},],
//	specializeTaxRate: [{ required: true, message: '请输入专票税率!'},],
	
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    formData.id = '';
    snapContactId.value = buildShortUUID('temporary_id_del');
    const defaultValueRef = reactive<Record<string, any>>({
      id: snapContactId.value,
    });
    edit(defaultValueRef);
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });

  }
  async function info(id) {
   const rest = await getQueryById({'id':id})
    if(rest){
       const record = rest
      nextTick(() => {
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(record.hasOwnProperty(key)){
            tmpData[key] = record[key]
          }
        })
        //赋值
        Object.assign(formData, tmpData);
      });
    }

  }
  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    debugger
    if (model.id && !model.id.includes("temporary_id_del")) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
    info,
    snapContactId,

  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
